package io.bluerain.adbdlistenerauto;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import io.bluerain.adbdlistenerauto.entities.StatusInfo;

public class MainActivity extends AppCompatActivity {

    CoreService.CoreBinder binder;
    CoreService.SwitchStatus status = CoreService.SwitchStatus.NORMAL;
    CoreService.SwitchStatus bootStatus = CoreService.SwitchStatus.NORMAL;
    static int NETWORK = 0x1;
    static String KEY_STATUS = "status";
    static String KEY_BOOT_STATUS = "bootStatus";
    static String STATUS_INFO = "statusInfo";
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    Switch bootSwitch, switcher;
    TextView txtNetWork, txtIpAddress;
    CompoundButton.OnCheckedChangeListener bootListener, switcherListener;
    Handler handler;
    ServiceConnection con;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化成员变量
        init();
        //更新网络UI
        updateNetWorkStatus();
        System.out.println(getLocalIPAddress());
    }

    private void init() {
        preferences = getSharedPreferences("als", Context.MODE_PRIVATE);
        editor = preferences.edit();
        bootSwitch = (Switch) findViewById(R.id.switcher_boot);
        switcher = (Switch) findViewById(R.id.switcher);
        txtNetWork = (TextView) findViewById(R.id.txt_net_work);
        txtIpAddress = (TextView) findViewById(R.id.txt_ip_address);
        bootListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    bootStatus = CoreService.SwitchStatus.ON;
                    //开机自动器
                    editor.putInt(KEY_BOOT_STATUS, CoreService.SwitchStatus.ON.getValue());
                } else {
                    bootStatus = CoreService.SwitchStatus.OFF;
                    //禁止开机自启
                    editor.putInt(KEY_BOOT_STATUS, CoreService.SwitchStatus.OFF.getValue());
                }
                editor.commit();
            }
        };
        con = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                binder = (CoreService.CoreBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        switcherListener = new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //开启
                    status = CoreService.SwitchStatus.ON;
                    if (binder != null)
                        binder.status(CoreService.SwitchStatus.ON);
                } else {
                    //关闭
                    status = CoreService.SwitchStatus.OFF;
                    if (binder != null)
                        binder.status(CoreService.SwitchStatus.OFF);
                }
                editor.putInt(KEY_STATUS, status.getValue());
                startService(getIntent(new StatusInfo(status, null)));
                editor.commit();
            }
        };
        switcher.setOnCheckedChangeListener(switcherListener);
        bootSwitch.setOnCheckedChangeListener(bootListener);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == NETWORK) { //更新网络状态UI
                    Bundle bundle = msg.getData();
                    String networkName = "所在局域网:" + bundle.getString("ssid");
                    String ip = "内网IP地址:" + bundle.getString("ip");
                    txtNetWork.setText(networkName);
                    txtIpAddress.setText(ip);
                }
            }
        };
        if (preferences.getInt(KEY_STATUS, -1) == -1) { //没有配置
            editor.putInt(KEY_BOOT_STATUS, CoreService.SwitchStatus.ON.getValue());
            editor.putInt(KEY_STATUS, CoreService.SwitchStatus.ON.getValue());
            editor.commit();
        }
        readPreferences(); //读取配置+更新UI
        //绑定Service
        bindService(getIntent(new StatusInfo(status, null)), con, Service.BIND_AUTO_CREATE);
    }

    private void updateNetWorkStatus() {
        //获取网络参数WIFI名称以及内网IP地址
        new Thread(new Runnable() {
            @Override
            public void run() {
                //获取WIFI名称
                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ssid = wifiInfo.getSSID();
                String ip = getLocalIPAddress();
                Bundle bundle = new Bundle();
                bundle.putString("ssid", ssid);
                bundle.putString("ip", ip);
                Message message = new Message();
                message.setData(bundle);
                message.what = NETWORK;
                handler.sendMessage(message);
            }
        }).start();
    }

    private Intent getIntent(StatusInfo info) {
        final Intent intent = new Intent(MainActivity.this, CoreService.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(STATUS_INFO, info);
        intent.putExtras(bundle);
        return intent;
    }

    private void readPreferences() {
        status = CoreService.SwitchStatus.get(preferences.getInt(KEY_STATUS, 0));
        bootStatus = CoreService.SwitchStatus.get(preferences.getInt(KEY_BOOT_STATUS, 0));
        switch (status) {
            case NORMAL:
            case ON:
                switcher.setChecked(true);
                break;
            case OFF:
                switcher.setChecked(false);
                break;
        }
        switch (bootStatus) {
            case NORMAL:
            case ON:
                bootSwitch.setChecked(true);
                break;
            case OFF:
                bootSwitch.setChecked(false);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(con);
    }

    public String getLocalIPAddress() {
        String localip = null;// 本地IP，如果没有配置外网IP则返回它
        String netip = null;// 外网IP

        Enumeration<NetworkInterface> netInterfaces =
                null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress ip = null;
        boolean finded = false;// 是否找到外网IP
        while (netInterfaces.hasMoreElements() && !finded) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                /*if (!ip.isSiteLocalAddress()
                        && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                } else */
                if (ip.isSiteLocalAddress()
                        && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
                    localip = ip.getHostAddress();
                }
            }
        }

        if (localip != null && !"".equals(localip)) {
            return localip;
        } else {
            return "未识别";
        }
    }

}
